package com.qiaofang.collectmanagebff.service.util.upload;

import com.qiaofang.common.util.DateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Pattern;

public abstract class AbstractExcelUploader extends AbstractUploader{

    protected static String REGEX_MOBILE = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";

    protected static Pattern p = Pattern.compile(REGEX_MOBILE);

    public final static String SUCCESS = "导入成功";
    public final static String FAILURE = "导入失败";

    // 新版房源采集-中介标题
    public final static String SYS_PRO_TITLE_HOUSE_AGENT_NAME = "姓名";
    public final static String SYS_PRO_TITLE_HOUSE_AGENT_TEL = "电话";

    // 新版房源采集-中介导入标题（系统默认标题）
    public final static String[] SYS_PRO_TITLE_HOUSE_AGENT = {
            SYS_PRO_TITLE_HOUSE_AGENT_NAME, SYS_PRO_TITLE_HOUSE_AGENT_TEL
    };


    public final static Map<String, Object>  HOUSE_AGENT_TEMPLATE_MAP = new HashMap<String, Object>();


    public final static int maxCountOfImportCaifang = 300;

    public final static int maxCountOfImportAgentHouse = 10000;

    static {
        // 中介模板数据
        HOUSE_AGENT_TEMPLATE_MAP.put(SYS_PRO_TITLE_HOUSE_AGENT_NAME, "张先生");
        HOUSE_AGENT_TEMPLATE_MAP.put(SYS_PRO_TITLE_HOUSE_AGENT_TEL, "15912345678");
    }

    /**
     * 创建默认工作薄
     *
     * @return
     */
    public Workbook createDefaultWorkbook() {
        return new HSSFWorkbook();
    }

    public Workbook createDefaultXssfWorkbook(){
        return  new XSSFWorkbook();
    }

    /**
     * 导出 Excel
     *
     * @param response
     * @param workBook
     * @param writeFileName
     * @throws Exception
     */
    public void writeExcel(
            HttpServletResponse response, Workbook workBook, String writeFileName) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(URLEncoder.encode(writeFileName, "UTF-8")));
        response.setContentType("application/octet-stream");
        ServletOutputStream outPutStream = response.getOutputStream();
        workBook.write(outPutStream);
        outPutStream.flush();
        outPutStream.close();
    }

    /**
     * 下载导入模板
     *
     * @param title
     * @param dataMap
     * @param response
     * @param templateName
     */
    public void downloadTemplate(String[] title,
                                 Map<String, Object> dataMap,
                                 HttpServletResponse response,HttpServletRequest request,
                                 String templateName) {
        if (title == null || title.length == 0
                || dataMap == null || dataMap.size() == 0) {
            return;
        }

        Workbook workbook = createDefaultWorkbook();
        Sheet sheet = workbook.createSheet();
        Row rowTitle = sheet.createRow(0);
        String[] sysTitles = title;
        Map<String, Integer> titleMap = new HashMap<String, Integer>();
        for (int i = 0; i < sysTitles.length; i++) {
            Cell cell = rowTitle.createCell(i);
            cell.setCellValue(sysTitles[i]);
            titleMap.put(sysTitles[i], i);
        }
        Row row = sheet.createRow(1);
        Set<Map.Entry<String, Object>> set = dataMap.entrySet();
        Iterator<Map.Entry<String, Object>> it = set.iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            if (titleMap.containsKey(entry.getKey())) {
                Cell cell = row.createCell(titleMap.get(entry.getKey()));
                Object value = entry.getValue();
                if (value instanceof String) {
                    cell.setCellValue((String) entry.getValue());
                } else if (value instanceof Integer) {
                    cell.setCellValue((Integer) entry.getValue());
                } else if (value instanceof Date) {
                    cell.setCellValue((Date) entry.getValue());
                    cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                    CellStyle cellStyle = workbook.createCellStyle();
                    DataFormat dataFormat = workbook.createDataFormat();
                    cellStyle.setDataFormat(dataFormat.getFormat(DateUtil.YYYY_MM_DD));
                    cell.setCellStyle(cellStyle);
                } else if (value instanceof Float) {
                    cell.setCellValue((Float) entry.getValue());
                } else if (value instanceof Double) {
                    cell.setCellValue((Double) entry.getValue());
                } else if (value instanceof Boolean) {
                    cell.setCellValue((Boolean) entry.getValue());
                }
            }
        }
        try {
           writeExcel(response, workbook, templateName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void downloadFailureData(Long importDate, HttpServletResponse response) throws Exception{
        return;
    }
}
